import { Button, Input, Layout, Select, TableProps, Tabs, TabsProps, Tag } from 'antd';
import './style/index.css';
import AppPermissionContent, { DefaultValueProps } from './components/AppPermissionContent';
import { useCallback, useEffect, useMemo, useState } from 'react';
import appService from '@/api/services/appService';
import {
  ApprovedList,
  GetDatasetList,
  GetPoliciesRes,
  GetRoleRes,
  GetRolesUserList,
  GetRolesUserReq,
  PoliciesRevokeReq,
  ReloRevokeReq,
  SetPoliciesReq,
  TargetUsers,
} from '@/common/types';
import PagesHeader from '@/components/pages-header';
import useDragResize from '@/hooks/use-drag-resize';
import { SearchOutlined } from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';
import './style/index.css';
import { formatData } from '@/utils/time';
import orgService from '@/api/services/orgService';
import useModal from '@/hooks/use-modal/useModal';
import Tables from '@/components/tables/tables';
import logo from '@/assets/icons/ai-logo-eai.svg';
import aiaalogo from '@/assets/images/aiaaLogo.png';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import useTable from '@/hooks/use-table';
import NotData from '@/components/NotData';
import PersonnelModal, { SubmitType } from '@/components/personnel-modal/personnel-modal';
import KnowPermissionsModal from '@/components/know-permissions-modal/know-permissions-modal';
import TipsModals from '@/components/modals/TipsModals';
import { debounce } from 'lodash';
import { CircleLoading } from '@/components/loading';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import TipDesc from '@/components/tipDesc/tipDesc';

type SharedFields = keyof TargetUsers & keyof GetPoliciesRes;
type ExclusiveFields = Partial<
  Omit<TargetUsers, SharedFields> & Omit<GetPoliciesRes, SharedFields>
>;

type TableDatas = Pick<TargetUsers, SharedFields> & ExclusiveFields;

type RoleCode = 'admin' | 'knowledge_manager' | 'knowledge_reviewer';

export interface Option {
  key?: string;
  value: string;
  label: React.ReactNode;
  name?: string;
  resource_type?: string;
  children?: Option[];
  isLeaf?: boolean;
  parentId?: null | string;
  type?: string;
}

interface TablesData {
  admin: TableDatas[];
  knowledge_manager: TableDatas[];
  knowledge_reviewer: TableDatas[];
  qa: TableDatas[];
}

export default function AppPermissionManage() {
  const [value, setValue] = useState<ApprovedList[]>([]);
  // const [selectValue, setSelectValue] = useState<string>('');
  const [selectData, setSelectData] = useState<ApprovedList>();

  // const { configurations } = useOrchestrationStore();

  // const isDisableDataset = useMemo(
  //   () =>
  //     configurations?.find((config) => config.name === 'disable_dataset')?.default_value === '1' ||
  //     false,
  //   [],
  // );

  const [tabsItems, setTabsItems] = useState<TabsProps['items']>([
    {
      key: 'admin',
      label: '应用管理员',
    },
    {
      key: 'knowledge_manager',
      label: '知识库管理员',
      // disabled: isDisableDataset,
    },
    {
      key: 'knowledge_reviewer',
      label: '知识库审批员',
      // disabled: isDisableDataset,
    },
    {
      key: 'qa',
      label: '问答人员',
    },
  ]);

  const [option, setOption] = useState<Option[]>([
    {
      key: 'dataset',
      value: '*',
      type: 'dataset',
      label: '知识库文件',
      name: '知识库文件',
      children: [],
      isLeaf: false,
      parentId: null,
    },
    {
      key: 'function',
      value: '*',
      type: 'function',
      label: '数据接口',
      name: '数据接口',
      children: [],
      isLeaf: false,
      parentId: null,
    },
  ]);

  const [deleteData, setDeleteData] = useState<ReloRevokeReq | PoliciesRevokeReq>();

  const [tablesData, setTablesData] = useState<any[]>([]);

  const [qaData, setQaData] = useState<any[]>([]);

  const [tabsValue, setTabsValue] = useState<string>('admin');

  const [resizeWidth, handleMouseDown] = useDragResize({ width: 344, maxWidth: 480 });

  const modal = useModal('update', 'personnel', 'delete', 'edit');

  const [contentLoading, setContentLoading] = useState<boolean>(false);

  const [appLoading, setAppLoading] = useState<boolean>(false);

  const [pagination, setPagination] = useState<GetRolesUserReq>({
    offset: -1,
    page: 1,
    page_size: 20,
    app_id: '',
    searchText: '',
  });

  const [total, setTotal] = useState<number>(0);

  const [modalTitle, setModalTitle] = useState<string>('');

  const [disableData, setDisableData] = useState<any>([]);

  const [defaultTablesValue, setDefaultTablesValue] = useState();

  const [selectUser, setSelectUser] = useState<SubmitType[] | DefaultValueProps[]>([]);

  const [editType, setEditType] = useState<boolean>(false);

  const [searchText, setSearchText] = useState<string>('');

  const [approvedSearchText, setApprovedSearchText] = useState<string>('');

  const [tablesLoading, setTablesLoading] = useState<boolean>(false);

  const [adminInfo, setAdminInfo] = useState<GetRolesUserList[]>([]);

  const handleChange = (item: ApprovedList) => {
    setTabsItems((prev) => {
      if (!prev) return prev;

      return prev.map((v) => {
        if (v.key === 'knowledge_manager' || v.key === 'knowledge_reviewer') {
          return { ...v, disabled: item.disable_dataset };
        }

        return v;
      });
    });

    getDataset(item?.app_id as string, item);
    setSelectData(item);
  };

  useEffect(() => {
    getApproved();
  }, []);

  const getApproved = (searchText?: string) => {
    setAppLoading(true);
    appService
      .getApproved(searchText)
      .then((res) => {
        setValue(res.list);
      })
      .finally(() => {
        setAppLoading(false);
      });
  };

  const formatDataset = (value: GetDatasetList[]): Option[] => {
    return value.map((item) => {
      return {
        key: item._id,
        value: item._id,
        type: item.type,
        label: item.name,
        name: item.name,
        children: item.children ? formatDataset(item.children) : [],
        parentId: item.parentId,
      };
    });
  };

  useEffect(() => {
    if (selectData) {
      getRoleInfo();
      handleTabsClick('admin');
    }
  }, [selectData]);

  const getRoleInfo = () => {
    // orgService.getRolesBasic(selectData?.app_id as string).then((res) => {
    orgService.getRolesBasic(selectData?.app_id as string).then((res) => {
      const roleLabelMap = {
        admin: '应用管理员',
        knowledge_manager: '知识库管理员',
        knowledge_reviewer: '知识库审批员',
        qa: '问答人员',
      };

      res.map((value) => {
        const labelPrefix = roleLabelMap[value.code as RoleCode];
        if (labelPrefix) {
          setTabsItems((prev) =>
            prev?.map((item) =>
              item.key === value.code
                ? { ...item, label: `${labelPrefix}（${value.count}）` }
                : item,
            ),
          );
        }
      });
    });
  };

  const tableColumns: TableProps<TableDatas>['columns'] = [
    {
      title: '名称',
      dataIndex: 'name',
      width: '200px',
    },
    {
      title: '学/工号',
      dataIndex: 'user_id',
      render: (value) => <span>{value ? value : '-'}</span>,
    },
    {
      title: '所属组织',
      dataIndex: 'group',
      render: (_, { group }) => <span>{group?.name}</span>,
    },

    {
      title: '添加日期',
      dataIndex: 'create_time',
      render: (_, { create_time }) => <span>{formatData(create_time as string)}</span>,
    },
    {
      title: '操作',
      dataIndex: 'act',
      width: '200px',
      render: (_, record) => {
        return record.id === selectData?.create_user_id || record?.role.id === 'admin' ? null : (
          <a className="!text-@error-color" onClick={() => handleDelete(record)}>
            删除
          </a>
        );
      },
    },
  ];

  const qaTableColumns: TableProps<TableDatas>['columns'] = [
    {
      title: '名称',
      key: 'index',
      width: '200px',
      render: (_, record) => <span>{record.target?.target_name}</span>,
    },
    {
      title: '类型',
      // dataIndex: 'type',
      key: 'index',
      // width: '80px',
      render: (_, record) => <span>{record.target?.target_type === 'user' ? '用户' : '组织'}</span>,
    },
    {
      title: '问答权限',
      // dataIndex: 'role',
      key: 'index',
      hidden: selectData?.disable_dataset,
      render: (_, record) => {
        if (!record.resources) {
          return <span>-</span>;
        }

        const dataset = [];
        const functions = [];

        for (let i = 0; i < record.resources.length; i++) {
          const data = record.resources[i];
          if (data.resource_type === '*' && data.resource_id === '*') {
            dataset.push({ name: '所有知识库', type: 'dataset' });
            functions.push({ name: '所有数据接口', type: 'function' });
            continue;
          }

          if (data.resource_type === 'dataset' && data.resource_id === '*') {
            dataset.push({ name: '所有知识库', type: 'dataset' });
            continue;
          }

          if (data.resource_type === 'function' && data.resource_id === '*') {
            functions.push({ name: '所有数据接口', type: 'function' });
            continue;
          }

          if (data.resource_type === 'database' && data.resource_id === '*') {
            functions.push({ name: '所有NL2SQL', type: 'database' });
            continue;
          }

          if (data.resource_type === 'folder') {
            dataset.unshift({ name: data.resource_name, type: 'folder' });
            continue;
          }

          if (data.resource_type === 'function') {
            functions.push({ name: data.resource_name, type: 'function' });
            continue;
          }

          dataset.push({ name: data.resource_name, type: 'dataset' });
        }

        return (
          <div className="flex flex-col gap-2">
            <div className="flex flex-wrap gap-2">
              {dataset.map((item, index) => (
                <Tag
                  color={item.type === 'folder' ? 'blue' : 'orange'}
                  key={index.toString()}
                  style={{ margin: 0 }}
                >
                  {item.name}
                </Tag>
              ))}
            </div>

            <div className="flex flex-wrap gap-2">
              {functions.map((item, index) => (
                <Tag color="green" key={index.toString()} style={{ margin: 0 }}>
                  {item.name}
                </Tag>
              ))}
            </div>
          </div>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'act',
      width: 200,
      render: (_, record) => (
        <>
          {!selectData?.disable_dataset && (
            <a className="!text-@brand-color" onClick={() => hanldeEditData(record)}>
              {'编辑'}
            </a>
          )}
          <a className="ml-5 !text-@error-color" onClick={() => handleDelete(record)}>
            删除
          </a>
        </>
      ),
    },
  ];

  const handleTabsClick = (key: string) => {
    setTabsValue(key);
    setPagination({ ...pagination, searchText: '' });
    setSearchText('');
    if (key !== 'qa') {
      getRolesUser(key);
      console.log(key);
    } else {
      // orgService.getPolicies({ app_id: selectData?.app_id as string }).then((res) => {
      // orgService.getPolicies({ app_id: app_id as string }).then((res) => {
      //   setQaData(res);
      //   // console.log(res);
      // });
      getPoliciesPage(key);
    }
  };

  const getRolesUser = (key: string, paginationValue?: GetRolesUserReq) => {
    setTablesLoading(true);
    const paginationInfo = paginationValue || pagination;
    orgService
      // .getRolesUser({ ...pagination, role_code: key, app_id: selectData?.app_id as string })
      .getRolesUser({ ...paginationInfo, role_code: key, app_id: selectData?.app_id as string })
      .then((res) => {
        setTablesData(res.list);
        setTotal(res.total);
        if (key === 'admin') {
          setAdminInfo(res.list);
        }
      })
      .finally(() => {
        setTablesLoading(false);
      });
  };

  const getPoliciesPage = (key: string, paginationValue?: GetRolesUserReq) => {
    setTablesLoading(true);
    const paginationInfo = paginationValue || pagination;
    orgService
      .getPoliciesPage({ ...paginationInfo, app_id: selectData?.app_id as string })
      .then((res) => {
        setQaData(res.list);
        setTotal(res.total);
      })
      .finally(() => {
        setTablesLoading(false);
      });
  };

  /**
   * @description: 新增用户弹窗
   * @return {*}
   */
  const hanldeUpdate = () => {
    if (tabsValue === 'admin') {
      setModalTitle('应用管理员');
    }
    if (tabsValue === 'knowledge_manager') {
      setModalTitle('知识库管理员');
    }

    if (tabsValue === 'knowledge_reviewer') {
      setModalTitle('知识库审批员');
    }

    if (tabsValue === 'qa') {
      setModalTitle('问答人员');
    }

    const temp = tablesData.find((item) => item.code === 'admin');

    if (tabsValue !== 'qa') {
      if (tabsValue !== 'admin') {
        setDefaultTablesValue([...tablesData, ...adminInfo]);
      } else {
        setDefaultTablesValue(tablesData);
      }
    } else {
      const temp = qaData.map((item) => {
        return {
          id: item.target?.target_id,
          name: item.target?.target_name,
          resources: item.resources,
          type: item.target?.target_type,
        };
      });

      setDefaultTablesValue(temp);
    }

    if (tabsValue !== 'admin') {
      setDisableData(temp ? [...temp, ...adminInfo] : [...adminInfo]);
    } else {
      setDisableData([{ id: selectData?.create_user_id }]);
    }

    // 其他
    modal.update.open();
  };

  const handlePersonnelSubmit = (value: SubmitType[]) => {
    if (tabsValue === 'qa') {
      if (selectData?.disable_dataset) {
        const result = value.map((item) => ({
          resources: [
            {
              action: 'qa',
              resource_id: '*',
              resource_type: '*',
            },
          ],
          target: {
            target_type: item.type,
            target_id: item.id,
          },
        }));

        orgService
          .setPolicies({ app_id: selectData?.app_id as string, statements: result })
          .then((res) => {
            // getPolicies();
            handleTabsClick(tabsValue);
            getRoleInfo();
            modal.update.close();
            modal.personnel.close();
          });
        return;
      }

      setSelectUser(value);
      modal.personnel.open();
      return;
    }

    modal.update.startLoading();
    orgService
      .assignRole({
        app_id: selectData?.app_id as string,
        role_code: tabsValue as 'admin' | 'knowledge_manager' | 'knowledge_reviewer',
        user_ids: value.map((item) => item.id),
      })
      .then((res) => {
        handleTabsClick(tabsValue);
        modal.update.close();
        getRoleInfo();
      })
      .finally(() => {
        modal.update.stopLoading();
      });
  };

  const getDataset = async (app_id: string, appInfo?: ApprovedList) => {
    setContentLoading(true);
    try {
      const data = orgService.getDataset({ appId: app_id });

      const dataset = (await data).list.filter((item) => item.type !== 'function');
      const functionDataset = (await data).list.filter((item) => item.type === 'function');

      const formatDatasetData = formatDataset(dataset);
      const formatFunctiontData = formatDataset(functionDataset);

      await setContentLoading(false);

      if (appInfo !== undefined) {
        let result = [
          {
            key: 'dataset',
            value: 'datasetRoot',
            type: 'dataset',
            label: '知识库文件',
            name: '知识库文件',
            children: formatDatasetData,
            isLeaf: false,
            parentId: null,
          },
        ];

        if (appInfo.enable_function_calling) {
          result.push({
            key: 'function',
            value: 'functionRoot',
            type: 'function',
            label: '数据接口',
            name: '数据接口',
            children: formatFunctiontData,
            isLeaf: false,
            parentId: null,
          });
        }
        const nl2sql = await orgService.getDatasetNl2sql({ appId: app_id })
        console.log('nl2sql', nl2sql);
        
        // 转换 nl2sql 数据格式
        if (nl2sql?.list && nl2sql.list.length > 0) {
          const nl2sqlChildren = nl2sql.list.map((item) => ({
            key: item._id,
            value: item._id,
            type: 'database',
            label: item.name,
            name: item.name,
            children: [],
            isLeaf: true,
            parentId: null,
          }));
          
          // 添加 NL2SQL 选项到 result 数组
          result.push({
            key: 'database',
            value: 'databaseRoot',
            type: 'database',
            label: '数据库问答',
            name: '数据库问答',
            children: nl2sqlChildren,
            isLeaf: false,
            parentId: null,
          });
        }
        
        console.log('result', result);
        setOption(result);
      }
    } catch (e) {
      console.log(e);
    }
  };

  const handleKnowSubmit = (value: SetPoliciesReq['statements']) => {
    if (editType) {
      orgService
        .setPoliciesOne({ app_id: selectData?.app_id as string, statement: value[0] })
        .then((res) => {
          modal.personnel.close();
          modal.update.close();
          handleTabsClick(tabsValue);
          setEditType(false);
          getRoleInfo();
        });
    } else {
      orgService
        .setPolicies({ app_id: selectData?.app_id as string, statements: value })
        .then((res) => {
          modal.personnel.close();
          modal.update.close();
          handleTabsClick(tabsValue);
          setEditType(false);
          getRoleInfo();
        });
    }
  };

  const handleDelete = (value: TableDatas) => {
    if (value.id) {
      setDeleteData({
        app_id: selectData?.app_id as string,
        role_code: tabsValue,
        user_ids: [value?.id],
      });
    } else {
      setDeleteData({
        app_id: selectData?.app_id as string,
        target: {
          target_id: value.target?.target_id as string,
          target_type: value.target?.target_type as string,
        },
      });
    }
    modal.delete.open();
  };

  const handleDeleteData = () => {
    if (!deleteData) {
      return;
    }

    modal.delete.startLoading();
    if ('role_code' in deleteData && 'user_ids' in deleteData) {
      orgService
        .roleRevoke(deleteData)
        .then((res) => {
          handleTabsClick(tabsValue);
          getRoleInfo();
          modal.delete.close();
        })
        .finally(() => {
          modal.delete.stopLoading();
        });
    } else {
      orgService
        .policiesRevoke(deleteData)
        .then((res) => {
          modal.delete.close();
          handleTabsClick(tabsValue);
          getRoleInfo();
          // getPolicies();
        })
        .finally(() => {
          modal.delete.stopLoading();
        });
    }
  };

  const hanldeEditData = (value: TableDatas) => {
    // hanldeUpdate([value])
    setEditType(true);
    setSelectUser([
      {
        id: value.target?.target_id || '',
        name: value.target?.target_name || '',
        resources: value.resources || [],
        type: value.target?.target_type || 'user',
      },
    ]);
    modal.personnel.open();
  };

  const handlePagination = (page: number, pageSize: number) => {
    setPagination({ ...pagination, page: page, page_size: pageSize });
    if (tabsValue !== 'qa') {
      getRolesUser(tabsValue, { ...pagination, page: page, page_size: pageSize });
    } else {
      getPoliciesPage(tabsValue, { ...pagination, page: page, page_size: pageSize });
    }
  };

  const handleSearchText = (text: string) => {
    setSearchText(text);
    handlePaginationSearchTextFn(text);
  };

  const handlePaginationSearchText = (text: string) => {
    const paginantionInfo = { ...pagination, searchText: text };
    setPagination(paginantionInfo);
    if (tabsValue !== 'qa') {
      getRolesUser(tabsValue, paginantionInfo);
    } else {
      getPoliciesPage(tabsValue, paginantionInfo);
    }
  };

  const handlePaginationSearchTextFn = useCallback(
    debounce((text: string) => {
      handlePaginationSearchText(text);
    }, 500),
    [pagination, tabsValue],
  );

  const handleApprovedSearchText = (text: string) => {
    setApprovedSearchText(text);
    handleApprovedSearchTextFn(text);
  };

  const handleApprovedSearchTextFn = useCallback(
    debounce((text: string) => {
      getApproved(text);
    }, 500),
    [],
  );

  return (
    <div className="flex min-h-full flex-col">
      {/* <PagesHeader>应用权限管理</PagesHeader> */}
      <div className="flex h-full flex-1">
        <div
          className="h-[calc(100vh-16px)] overflow-hidden rounded-xl bg-white"
          style={{
            width: resizeWidth,
          }}
        >
          <div className="mb-4 ml-4 mt-4 text-base font-font-weight-600 text-text-5">
            应用权限管理
            <TipDesc title='管理哪些用户/部门可以问答或使用特定智能体应用' />
          </div>
          <div className="px-3">
            <Input
              placeholder="搜索"
              suffix={<SvgIcon icon="work-ic6" size={16} />}
              style={{
                // borderColor: '#C9CEE2',
                marginBottom: '10px',
              }}
              value={approvedSearchText}
              onChange={(e) => handleApprovedSearchText(e.target.value)}
            />
          </div>

          <div className="scrollbar overflow-y-auto" style={{ height: 'calc(100% - 110px)' }}>
            {appLoading ? (
              <>
                <CircleLoading />
              </>
            ) : (
              value.map((item) => (
                <div
                  key={item.app_id}
                  className={`flex cursor-pointer items-center py-[6px] pl-8 text-@brand-color hover:bg-@brand-color-light hover:text-@brand-color ${selectData?.app_id === item.app_id ? 'bg-@brand-color-light' : 'text-[#1D1D1D] '
                    }`}
                  onClick={() => handleChange(item)}
                // onClick={() => handleChange(item.app_id as string)}
                >
                  <AvatarDisplay src={item.avatar} size={16} className="h-4 w-4" />
                  <div
                    className="ml-1 truncate text-sm leading-9"
                    style={{
                      width: resizeWidth - 84,
                    }}
                  >
                    {item.name}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        <div
          className="group flex w-4 cursor-col-resize items-center justify-center bg-bg-1 py-2"
          onMouseDown={handleMouseDown}
        >
          <div className="hidden h-full  w-[2px] rounded-default bg-line-2 py-2 group-hover:block" />
        </div>

        <div className="flex h-[calc(100vh-16px)] flex-1 flex-col overflow-y-auto rounded-xl bg-white p-6 pb-0">
          {contentLoading ? (
            <>
              <CircleLoading />
            </>
          ) : (
            <>
              {selectData ? (
                <>
                  <Tabs items={tabsItems} onTabClick={handleTabsClick} activeKey={tabsValue} />
                  <div className="mb-4 mt-2 flex items-center justify-between">
                    <Input
                      style={{ width: 240 }}
                      placeholder="请输入内容"
                      suffix={<SvgIcon icon="work-ic6" size={16} />}
                      value={searchText}
                      onChange={(e) => handleSearchText(e.target.value)}
                    />
                    <Button
                      style={{
                        color: 'var(--brand-color)',
                        background: '#fff',
                        borderColor: 'var(--brand-color)',
                        padding: '0 12px 0px 8px'
                      }}
                      onClick={() => hanldeUpdate()}
                    >
                      <SvgIcon icon="add" color="var(--brand-color)" size={16} />
                      新增
                    </Button>
                  </div>
                  <Tables
                    columns={tabsValue === 'qa' ? qaTableColumns : tableColumns}
                    dataSource={tabsValue === 'qa' ? qaData : tablesData}
                    paginationProps={{
                      total: total,
                      pageSize: pagination.page_size,
                      current: pagination.page,
                      onChange: handlePagination,
                    }}
                    loading={tablesLoading}
                    rowKey={(record) => (tabsValue === 'qa' ? record.target.target_id : record.id)}
                  />
                </>
              ) : (
                <NotData fontText="请选择应用来管理相应权限" />
              )}
            </>
          )}
        </div>
      </div>

      <PersonnelModal
        title={`选择${modalTitle}`}
        appId={selectData?.app_id as string}
        onSubmit={handlePersonnelSubmit}
        isCheckBox={tabsValue === 'qa'}
        open={modal.update.isOpen}
        onCancel={modal.update.close}
        confirmLoading={modal.update.isLoading}
        defaultValue={defaultTablesValue}
        disabled={disableData}
      />

      <KnowPermissionsModal
        open={modal.personnel.isOpen}
        onCancel={modal.personnel.close}
        userData={selectUser}
        options={option}
        onSubmit={handleKnowSubmit}
        isKnow={selectData?.enable_function_calling}
      />

      <TipsModals open={modal.delete.isOpen} onCancel={modal.delete.close} onOk={handleDeleteData}>
        确认要删除用户信息，删除后无法恢复
      </TipsModals>
    </div>
  );
}
